package com.ytjj.qmyx.users.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.github.wxpay.sdk.WXPayUtil;
import com.ytjj.qmyx.users.service.WeChatReceiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

@RestController
@Slf4j
public class WeChatReceiveController {

    @Value("${wexin.receive.token}")
    private String TOKEN;

    @Autowired
    private WeChatReceiveService weChatReceiveService;

    /**
     * 推送接口
     * @return
     */
    @RequestMapping(value = "/receive")
    public String receive(HttpServletRequest request) throws Exception {
        String xmlResult = getWxRes(request);
        Map<String,String> notifyMap = WXPayUtil.xmlToMap(xmlResult);
        String event = notifyMap.get("Event");                                 // 事件类型
        String msgType = notifyMap.get("MsgType");                               // 消息类型
        log.debug("推送消息："+ JSONUtils.toJSONString(notifyMap));
        // 会员卡领取消息推送
        if("user_get_card".equals(event) && "event".equals(msgType)){
            weChatReceiveService.saveReceive(notifyMap);
        }
        String resultXML = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
        return resultXML;
    }

    /**
     * 微信验证token
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(value = "/checkToken",produces = "text/html;charset=utf-8")
    public String checkToken(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                             @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        // 检查token是否匹配
        String result = getEchostr(signature,timestamp,nonce,echostr);
        if(StringUtils.isNotBlank(result)){
            return result;
        }
        return null;
    }

    private String getEchostr(String signature, String timestamp,String nonce, String echostr){
        //排序
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1Hex 加密
        MessageDigest md = null;
        String temp = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            temp = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if ((temp.toLowerCase()).equals(signature)){
            return echostr;
        }
        return null;
    }

    /**
     * 获取微信响应
     *
     * @param request
     * @return
     * @throws IOException
     */
    private String getWxRes(HttpServletRequest request) throws IOException {
        String resXml = "";
        InputStream inputStream = request.getInputStream();
        //将InputStream转换成xmlString
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        resXml = sb.toString();
        log.debug(resXml);
        return resXml;
    }

    private static String byteToStr(byte[] byteArray){
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte){
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
}


